#! /usr/bin/perl -w

use strict;

use CGI::FOGE2::Test;
use HTML::TokeParser;
use WWW::Mechanize;

# args of a testNN.pl program:
# name of the CGI script to call "http://.*/testNN.cgi"
# name "testNN.cgi"
# pguser (who will be allowed to empty the tables) ""

my ($url, $testname, $pguser) = @ARGV;
defined $pguser || die "Too few arguments";

my $pwd = `pwd`;
my $isatty = 1;

if (1) {
    `./erasetables foge_test00_01 foge_test00_answer $pguser` 
      || die "DELETE failed";
}

my $ag = WWW::Mechanize->new();
my $tst = CGI::FOGE2::Test->new($testname);
printf "Testing script at \`%s'\n", $url;
my $res;

# data to send: array of [n, hash*]
# n: how many times to submit this dataset
# hash: { field => <fieldname>, value => <value> }
my $submit_data =
  [
   [ 5,
     { field => 'favoriteFood', value => 'Donut'},
     { field => 'favoriteBeverage', value => 'Duff'}, ],
   [ 3,
     { field => 'favoriteFood', value => 'Pork Chop'},
     { field => 'favoriteBeverage', value => 'Chocobeer'}, ],
   [ 3,
     { field => 'favoriteFood', value => 'Pork Chop'},
     { field => 'favoriteBeverage', value => '-?-'}, ],
  ];
# the expected results: array of [n, ary*]
# n: total number of answers to this question
# ary: [<field value>, <pcent>, <# of answers>]
my $submit_results = 
  [
   [11, ['Donut', 45, 5], ['Pork Chop', 54, 6]],
   [11, ['Duff Ultra', 100, 11]],
  ];


# send test data (...)
foreach my $item (@$submit_data) {
    my $times = shift @$item;
    my $i;
    for ($i=0; $i<$times; ++$i) {
        $tst->testname("Retrieve($i)");
        $ag->get($url);
        $tst->testresult($ag->status() == 200, 1);

        $tst->testname("Get form 1($i)");
        $res= $ag->form(1);
        $tst->testresult($res,1);

        foreach my $hash (@$item) {
            $tst->testname("Fill field food($i)");
            $ag->field($hash->{field}, $hash->{value});
            $tst->testresult(1, 0);
        }

        $tst->testname("Fill field beverage($i)");
        $ag->field('favoriteBeverage', 'Duff Ultra');
        $tst->testresult(1, 0);

        $tst->testname("Click($i)");
        $tst->testresult(defined $ag->click(), 1);

        print "sleeping...\r" if $isatty;
        sleep 1;
    }
}

# retrieve the stats page
my $htp = HTML::TokeParser->new(\$ag->{content});

$tst->testname("RetrieveStats");
$ag->get($url."/see");
$tst->testresult($ag->status() == 200, 1);


foreach my $result (@$submit_results) {
    $tst->testname("GetTable0Row0");
    $htp->get_tag('table');

    {
	my $ tok = $htp->get_token();
	printf "<<<%s>>>", join " :: ", @$tok;
	$htp->unget_token($tok);
}
    $tst->testresult(defined($htp->get_tag('table')));

    my $table0 = $tst->html_to_array($htp);

    $tst->testname("Table0Line0Format", 1);

    if (defined $table0->[0]->[0] && $table0->[0]->[0] =~
        /^([\w ]+):\ +          # "Donut: "
        (\d+)%\ +               # "1% "
        \((\d+)\/(\d+)\)\ *     # (1\/55)
        $/x) {
        my ($fieldname, $pcent, $nb, $total) = ($1, $2, $3, $4);
        $tst->testresult(1);
        $tst->testname("Table0Line0Name", 0);
	printf STDERR "*** %s ***", $fieldname;
        $tst->testresult($fieldname eq $result->[1][0]);
        $tst->testname("Table0Line0Pcent", 0);
        $tst->testresult($pcent  == $result->[1][1]);
        $tst->testname("Table0Line0Freq", 0);
        $tst->testresult($nb     == $result->[1][2]);
        $tst->testname("Table0Line0Total", 0);
        $tst->testresult($total  == $result->[0]);
    } else {
        $tst->testresult(0);
    }
}

if (0) {
    my $tot = 0;
    $tst->testname("GetTable0Row1");
    $tst->testresult(defined($htp->get_tag('table')));

    my $table1 = $tst->html_to_array($htp);

    $tst->testname("Table0Line1Format", 1);
    if (defined $table1->[0]->[0] && $table1->[0]->[0] =~
        /^[\w ]+:\ +            # "Donut: "
        (\d+)%\ +               # "1% "
        \((\d+)\/(\d+)\)\ *     # (1\/55)
        $/x) {
        my ($pcent, $nb, $total) = ($1, $2, $3);
        $tst->testresult(1);
        $tst->testname("Table0Line1Values", 0);
        $tst->testresult(
                         $pcent == 100 && $nb == $tot && $total == $tot
                        );

    } else {
        $tst->testresult(0);
    }
}

# printf "%s\n", $table0->[0]->[1];
# printf "%s\n", $table0->[0]->[2];


$tst->finish();

=for comment

$tst->testname();
$tst->testresult();

$tst->testname();
$tst->testresult();

$tst->testname();
$tst->testresult();




# my $htp = HTML::TokeParser->new($agent->);

exit 0;

$htp->get_tag('table');
my $ary = $tst->html_to_array($htp);

# $ary =  [[1,4,7],   [2,5,8]  ];

print "[";
foreach my $line (@$ary) {
  print "\t(";
  foreach my $elem (@$line) {
    printf "%s; ", $elem;
  }
  print ")\n";
}
print "]\n";

=cut


